// pages/shop/shop.js
import { goodsList } from "../../api/goods"
import {baseURL, request} from"../../utils/request"
const camp = require("../../api/camp")
const goods = require("../../api/goods")

Page({

  /**
   * 页面的初始数据
   */
  data: {
    activeKey: 0,
    campList: [],
    goodsList: [],
    qrCodeSrc: '', // 二维码图片的URL
    showDialog: false,
    baseURL:baseURL,
    cartList: [],
    cartLength: [],
    showCart: false,
    ShowSave: false,
    amount: 0,
    campId: "",
  },

  

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getAppointmentCampList();
  },

  onStepperChange (event){
    console.log("onStepperChange enent",event);
    let index = event.currentTarget.dataset.index;
    var goodsList = this.data.goodsList;
    var cartList = this.data.cartList;
    goodsList[index].num = event.detail;
    cartList.push(goodsList[index])
    const uniqueCartList = cartList.filter((item,index,self) =>{
      return index === self.findIndex(obj => obj.goodsId === item.goodsId);
    });
    this.setData({
      goodsList: goodsList,
      cartList: uniqueCartList
    })
    console.log("uniqueCartList",uniqueCartList)
  },

  // 关闭弹窗的方法
  onClose() {
    this.setData({ 
      showDialog: false,
      showCart: false,
      ShowSave: false,
      
     });
  },
  customer(code) {
    goods.getQrCode(code).then(res=>{
      if (res.code === 200) {
        console.log("res",res)
        this.setData({
          qrCodeSrc: res.msg,
        });
        this.setData({ showDialog: true });
      }

    });
  },

  //根据当前用户id查询预约的营地
  getAppointmentCampList() {
    
    camp.getAppointmentByUserId(wx.getStorageSync("userInfo").userId).then(res=>{
      console.log(res)
      if(res.code==200){
        this.setData({
          campList: res.data
        })
      }
      if(res.data.length <= 0){
        return;
      }
      this.setData({
        campId: res.data[0].campId
      })
      let campId = res.data[0].campId
      this.getGoods(campId);
    })
  },
  //左侧营地切换时
  onChange(event){
    console.log("event", event)
    this.setData({
      campId: this.data.campList[event.detail].campId
    })
    let campId = this.data.campList[event.detail].campId
    this.getGoods(campId);
  },
  //根据营地id查询商品信息
  getGoods(campId){
    goods.goodsList({campId:campId}).then(res=>{
      if(res.code == 200){
        var _goodsList = res.data
        for(let i = 0;i< _goodsList.length;i++){
          _goodsList[i].num = 0;
        }
        this.setData({
          goodsList: _goodsList
        })
        //根据购物车缓存数据，调整右小角下标
        this.setCartList();
      }
    })
  },
  setCartList() {
    var cartList = wx.getStorageSync('cartList-'+this.data.campId)
    if (cartList && cartList.length>0){
      this.setData({
        cartList: cartList
      })
    }else {
      this.setData({
        cartList: []
      })
    }
    this.sumAmount();
    this.setGoodsNum();
  },
  //设置商品已经加入购物车的数量
  setGoodsNum(){
    var cartList = this.data.cartList;
    var goodsList = this.data.goodsList;
    for(let i = 0;i<cartList.length;i++){
      for (let i=0;i<cartList.length; i++){
        const goodsItem = goodsList[j];
        if(cartItem.goodsId == goodsItem.goodsId){
          goodsList[j].num = cartItem.num;
          break;
        }
      }
    }
    this.setData({
      goodsList: goodsList
    })
  },
  //当在商品数量变化时
  onStepperChange(event){
    console.log("onStepperChange event",event);
    let index = event.currentTarget.dataset.index;
    var goodsList = this.data.goodsList;
    var cartList = this.data.cartList;

    goodsList[index].num = event.detail;
    //当商品的选购数量改变时，同步购物车数量
    var tag = 0;
    for(let j=0;j<cartList.length;j++){
      if(goodsList[index].goodsId == cartList[j].goodsId){
        cartList.num = goodsList[index].num;
        tag++;
        break;
      }
    }
    if(tag == 0){
      cartList.push(goodsList[index])
    }
    const uniqueCartList = cartList.filter((item,index,self)=>{
      return index === self.findIndex(obj=>obj.goodsId === item.goodsId)&&item.num >0;
    });
    this.setData({
      goodsList:goodsList,
      cartList:uniqueCartList,
      cartLength:uniqueCartList.length
    })
    console.log("uniqueCartList",uniqueCartList)
    console.log("cartLength",this.data.cartLength)
    this.sumAmount();
  },
  //当在购物车数量变化时
  onCartStepperChange(event){
    console.log("onCartStepperChange event",event);
    let index=event.currentTarget.dataset.index;
    var cartList = this.data.cartList;
    cartList[index].num = event.detail;
    const uniqueCartList = cartList.filter((item,index,self)=>{
      return item.num>0;
    });
    //当购物车中数量变化时，同步下标
    var goodsList = this.data.goodsList;
    for(let j=0;j<goodsList.length;j++){
      if(cartList[index].goodsId == goodsList[j].goodsId){
        goodsList[j].num=cartList[index].num;
        break;
      }
    }
    this.setData({
      cartList: uniqueCartList,
      goodsList: goodsList
    })
    this.sumAmount();
  },
  //计算总价
  sumAmount(){
    var cartList = this.data.cartList;
    var amount = 0;
    for(let i =0;i<cartList.length;i++){
      const item = cartList[i];
      amount +=item.num * item.goodsPrice;
    }
    this.setData({
      amount: amount,
      cartLength: cartList.length
    })

    
    wx.setStorageSync('cartList-'+this.data.campId,this.data.cartList)
  },
  
  //保存数据库
  savedata(){
    var DBdata = {
      userId: wx.getStorageSync("userInfo").userId,
      campId: this.data.campId,
      total: this.data.cartLength,
      // 跳过支付环节，直接改成已付款
      status: 2,
      orderDetailList: this.data.cartList.map (item=>({
        goodsId: item.goodsId,
        num: item.num,
        price: item.goodsPrice*item.num,
        goodsPrice: item.goodsPrice,
        memberPrice: item.memberPrice
      }))
    }
    if (DBdata.total !=0){
      console.log("DBdata",DBdata)
      goods.orderSave(DBdata).then(res =>{
        if(res.code == 200&&res.msg!=null){
          console.log("msg",res.msg)
          this.onClose
          wx.setStorageSync('cartList-'+this.data.campId,"")
          this.setData({
            cartList: [],
          })
          this.customer(res.msg)
        }
      })
    }else {
      this.onClose
    }
    
  },
  //弹出购物车页面
  onShowCart(){
    this.setData({
      showCart: true
    })
  },
  //弹出结算页面
  onShowSave(){
    this.setData({
      showCart: false,
      ShowSave: true
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})